const { DataTypes } = require('sequelize')

module.exports = (sequelize) => {
  const Customer = sequelize.define('Customer', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    name: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: '客户名称'
    },
    code: {
      type: DataTypes.STRING(50),
      allowNull: true,
      unique: true,
      comment: '客户编码'
    },
    type: {
      type: DataTypes.ENUM('individual', 'enterprise'),
      defaultValue: 'individual',
      comment: '客户类型'
    },
    contact_person: {
      type: DataTypes.STRING(50),
      allowNull: true,
      comment: '联系人'
    },
    phone: {
      type: DataTypes.STRING(20),
      allowNull: true,
      comment: '联系电话'
    },
    email: {
      type: DataTypes.STRING(100),
      allowNull: true,
      validate: {
        isEmail: true
      },
      comment: '邮箱'
    },
    address: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: '地址'
    },
    city: {
      type: DataTypes.STRING(50),
      allowNull: true,
      comment: '城市'
    },
    province: {
      type: DataTypes.STRING(50),
      allowNull: true,
      comment: '省份'
    },
    postal_code: {
      type: DataTypes.STRING(20),
      allowNull: true,
      comment: '邮编'
    },
    country: {
      type: DataTypes.STRING(50),
      defaultValue: '中国',
      comment: '国家'
    },
    credit_limit: {
      type: DataTypes.DECIMAL(12, 2),
      defaultValue: 0,
      comment: '信用额度'
    },
    current_balance: {
      type: DataTypes.DECIMAL(12, 2),
      defaultValue: 0,
      comment: '当前余额'
    },
    payment_terms: {
      type: DataTypes.STRING(50),
      allowNull: true,
      comment: '付款条件'
    },
    tax_number: {
      type: DataTypes.STRING(50),
      allowNull: true,
      comment: '税号'
    },
    website: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: '网站'
    },
    notes: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: '备注'
    },
    status: {
      type: DataTypes.ENUM('active', 'inactive', 'blacklist'),
      defaultValue: 'active',
      comment: '客户状态'
    },
    created_by: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: '创建者ID'
    },
    created_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW
    },
    updated_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW
    }
  }, {
    tableName: 'customers',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    comment: '客户表',
    indexes: [
      {
        fields: ['name']
      },
      {
        fields: ['code']
      },
      {
        fields: ['type']
      },
      {
        fields: ['status']
      }
    ]
  })

  return Customer
}